import pdfplumber
import re

def extract_toc_with_pages(pdf_path):
    """
    提取目录的数据
    :param pdf_path:
    :return:
    """
    toc_start_pattern = re.compile(r"目\s*录|Contents", re.IGNORECASE)
    toc_end_patterns = [
        re.compile(r"附录|Appendix", re.IGNORECASE),
        re.compile(r"致谢|Acknowledgements", re.IGNORECASE),
        re.compile(r"参考文献|References", re.IGNORECASE),
        # re.compile(r"摘\s*要|Abstract", re.IGNORECASE),
        # re.compile(r"第\s*[\u4e00-\u9fa5]+\s*章"),
        # re.compile(r"^(\d+\.|[一二三四五六七八九十]+[．、])"),
        re.compile(r"^引言|图表目录|图例", re.IGNORECASE)
    ]

    toc_text = []
    in_toc = False
    start_page = None
    end_page = None

    with pdfplumber.open(pdf_path) as pdf:
        for page in pdf.pages:
            page_num = page.page_number  # 页码从1开始
            text = page.extract_text()
            if not text:
                continue

            lines = [line.rstrip('\n').strip() for line in text.split('\n')]
            for line in lines:
                # 记录起始页
                if not in_toc and toc_start_pattern.search(line):
                    in_toc = True
                    start_page = page_num  # 目录起始页
                    toc_text.append(line)
                    continue

                # 记录终止页
                if in_toc:
                    for pattern in toc_end_patterns:
                        if pattern.search(line):
                            end_page = page_num  # 终止发生的当前页
                            toc_text.append(f"[终止: {pattern.pattern} → {line}]")
                            in_toc = False
                            break
                    if not in_toc:
                        break

                    toc_text.append(line)

            # 提前终止扫描
            if in_toc and page_num == pdf.pages[-1].page_number:
                end_page = page_num  # 目录贯穿到最后一页
                in_toc = False

    # 计算页数
    if not start_page:
        return {"pages": 0, "text": "未找到目录"}

    end_page = end_page or start_page  # 目录仅有起始页（无明确终止）
    total_pages = end_page - start_page + 1

    return {
        "pages": total_pages,
        "start_page": start_page,
        "end_page": end_page,
        "text": toc_text if toc_text else []
    }
def getContentPages(pdf_path):
    pdf_path = "附件3/B2998.pdf"
    toc_result = extract_toc_with_pages(pdf_path)
    print(f"【目录页数统计】")
    print(f"起始页: {toc_result['start_page']}")
    print(f"终止页: {toc_result['end_page']}")
    print(f"总页数: {toc_result['pages']}")
    print("\n【原始目录文本】")
    for i, line in enumerate(toc_result['text'], 1):
        print(f"{i:3d} | {line}")

if __name__ == '__main__':
    getContentPages("附件3/B2998.pdf")
